package com.bawei.module_home

import android.os.Build
import android.os.Bundle
import android.view.Gravity
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.PopupWindow
import androidx.annotation.RequiresApi
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_base.RoutePath
import com.bawei.lib_common.cache.RecyclerCachePool
import com.bawei.lib_common.mvi.BaseMviFragment
import com.bawei.module_home.adapter.HomeListAdapter
import com.bawei.module_home.adapter.HomePlayAdapter
import com.bawei.module_home.cache.HomeItemCache
import com.bawei.module_home.databinding.FragmentHomePlayBinding
import com.bawei.module_home.entriy.CommentHolder
import com.bawei.module_home.entriy.CommentListEntriyItem
import com.bawei.module_home.entriy.SimpleVideoEntity
import com.bawei.module_home.intent.HomeViewIntent
import com.bawei.module_home.state.HomeUiState
import com.bawei.module_home.view.CommentDialogFragment
import com.bawei.module_home.vm.HomeViewmodel
import com.bawei.module_play.adapter.PlayListAdapter
import com.bawei.module_play.entriy.CommentEntriyItem
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.luck.picture.lib.adapter.holder.VideoViewHolder
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch


@AndroidEntryPoint
@Route(path = RoutePath.PATH_FRAGMENT_HOMEPLAY)
class HomePlayFragment : BaseMviFragment<FragmentHomePlayBinding>() {

    private val mViewModel:HomeViewmodel by activityViewModels()
    private var simpVideoList= mutableListOf<SimpleVideoEntity>()
    private lateinit var videoplayadapter:HomePlayAdapter
    var position:Int=0
    private var typeId=0
    private var channelId=""
    private  var itemid=""

    //评论列表
    private var commVideoList= mutableListOf<CommentListEntriyItem>()
    private lateinit var commlistadapter: com.bawei.module_home.adapter.PlayListAdapter



    override fun getLayoutId(): Int {
     return R.layout.fragment_home_play
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun initViews() {

        commlistadapter=com.bawei.module_home.adapter.PlayListAdapter(commVideoList)

       videoplayadapter= HomePlayAdapter(simpVideoList).apply {
           setOnItemClickListener(object :HomePlayAdapter.OnItemClickListener{
               override fun onItemChick(v: View, position: Int) {
                   when(v.id){
                       R.id.play_title -> {
                           ARouter.getInstance().build(RoutePath.PATH_PLAY_PAGE)
                               .withString("videoPath", simpVideoList[position].videopath)
                               .withString("userId", simpVideoList[position].userid)
                               .withInt("typeId", typeId)
                               .withString("channelId", channelId)
                               .withString("itemId",  simpVideoList[position].item_id)
                               .withInt("moduleType", 0)
                               .withString("title", simpVideoList[position].title)
                               .navigation()
                       }

                       R.id.play_message->{
                           itemid=simpVideoList[position].item_id
                           //设置布局
                           val view=LayoutInflater.from(context).inflate(com.bawei.module_play.R.layout.popuwindews_item,null)
                           //定义popuwindows
                           var popuwindows= PopupWindow(context)
                           popuwindows.contentView=view
                           popuwindows.isOutsideTouchable=true
                           popuwindows.isFocusable=true
                           popuwindows.width= WindowManager.LayoutParams.MATCH_PARENT
                           popuwindows.height=1000
                           popuwindows.showAtLocation(view,Gravity.BOTTOM,0,0)
                           popuwindows.setOnDismissListener {
                               popuwindows.dismiss()
                           }
                           //获取布局中的rv列表
                           var rv=view.findViewById<RecyclerView>(com.bawei.module_play.R.id.windowrv)
                           //评论适配器
                           rv.adapter = commlistadapter

                       }
                   }
               }

           })
       }
        mDatatBinding.rvVideoList.adapter=videoplayadapter
        //仿抖音页面
        val pageSnapHelper=PagerSnapHelper()
        pageSnapHelper.attachToRecyclerView(mDatatBinding.rvVideoList)

        // 添加滚动监听实现自动播放
        mDatatBinding.rvVideoList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                // 滚动停止时
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                    val snapView = pageSnapHelper.findSnapView(layoutManager)
                    val position = snapView?.let { layoutManager.getPosition(it) } ?: return
                    // 获取当前ViewHolder并播放视频
                    val viewHolder = recyclerView.findViewHolderForAdapterPosition(position) as? HomePlayAdapter.ItemViewHolder
                    viewHolder?.dataBinding?.gsy?.startPlayLogic()
                }
            }
        })

        //设置点击事件
    }

    override suspend fun sendViewIntent() {
        super.sendViewIntent()
        mViewModel.channel.send((HomeViewIntent.LoadSimpleVideoList("94349546935",1,15)))
        mViewModel.channel.send((HomeViewIntent.LoadVideoCommentList(itemid,0)))
    }

    override suspend fun collectUIState() {
        mViewModel.uiStateFlow.collect{
            when(it){
                is HomeUiState.LoadSimpleVideoSuccess ->{
                    simpVideoList.addAll(it.list)
                    videoplayadapter.notifyDataSetChanged()
                }
                is HomeUiState.LoadSimpleVideoFail ->{

                }
                is HomeUiState.LoadVideoCommentSuccess->{
                    commVideoList.addAll(it.list)
                }
                is HomeUiState.LoadVideoCommentFail->{

                }
                else->{

                }
            }
        }
    }


}